import { useEffect } from 'react'

import { getEntrancesListByTypeApi } from '@/api/app'
import { createQualificationTypeApi } from '@/api/sys/qualificationType'
import AekForm from '@/components/AekForm'
import AekModal, { PromiseThen } from '@/components/AekModal'
import { SYS_QUALIFICATION_TYPE_ENUM } from '@/utils/enum'
import { requestWithTry } from '@/utils/request'

const EditModal = ({ row = {} }) => {
  const [form] = AekForm.useForm()
  const { id } = row

  useEffect(() => {
    if (!row.id) return
    form.setFieldsValue({
      ...row,
      entranceId: row.entranceId?.split(',') || [],
      type: row.type?.split(',') || [],
    })
  }, [row.id])

  /** @type {import("@/components/AekForm").FormDataProps[]} */
  const formData = [
    {
      field: 'qualificationTypeName',
      label: '资质类型',
      formItemProps: {
        rules: [{ required: true }],
      },
      component: { name: 'Input' },
    },
    {
      field: 'entranceId',
      label: '系统',
      formItemProps: {
        rules: [{ required: true }],
      },
      component: {
        name: 'AekSelect',
        props: {
          api: getEntrancesListByTypeApi,
          mode: 'multiple',
          fieldNames: {
            value: 'entranceId',
            label: 'entranceName',
          },
        },
      },
    },
    {
      field: 'type',
      label: '类型',
      formItemProps: {
        rules: [{ required: true }],
      },
      component: {
        name: 'Select',
        props: {
          options: SYS_QUALIFICATION_TYPE_ENUM.options,
          mode: 'multiple',
        },
      },
    },
  ]

  const onOk = async () => {
    const values = await form.validateFields()
    const params = {
      id,
      ...values,
      entranceId: values.entranceId.join(','),
      type: values.type.join(','),
    }
    await requestWithTry(createQualificationTypeApi, params)
  }
  return (
    <AekModal title={id ? '编辑' : '新增'} width={500} onOk={onOk}>
      <AekForm form={form} formData={formData} />
    </AekModal>
  )
}

EditModal.PromiseThen = PromiseThen

export default EditModal
